<template>
	<WithFixedPageContainer
		v-model:page="page"
		@size-change="handleSizeChange"
		@current-change="handleCurrentChange"
	>
		<!-- 搜索表单 -->
		<div class="bg-white p-2 rounded-md">
			<BasicTableFrom :formList="formList" @search="handleSearch">
				<template #menu>
					<el-button type="primary" @click="handleAddNew">新增车队</el-button>
				</template>
			</BasicTableFrom>
		</div>

		<!-- 表格 -->
		<template #table>
			<div class="h-full overflow-auto">
				<BasicTable
					:data="tableData"
					:option="tableColumns"
					v-model:page="page"
					:table-loading="loading"
				>
					<!-- 自定义列插槽 -->
					<template #menu="{ row }">
						<el-button text type="primary" @click="handleEdit(row)"
							>编辑</el-button
						>
						<el-button
							text
							:type="row.fleetStatus === '1' ? 'danger' : 'primary'"
							@click="handleDelete(row)"
							>{{ row.fleetStatus === '1' ? '禁用' : '启用' }}</el-button
						>
					</template>

					<!-- 车辆数插槽 -->
					<template #vehicleNum="{ row }">
						<span v-if="!row.vehicleNum">0</span>
						<el-button
							v-else
							type="primary"
							link
							@click="handleViewVehicles(row)"
						>
							{{ row.vehicleNum }}
						</el-button>
					</template>

					<!-- 本月运单数插槽 -->
					<template #transportNum="{ row }">
						<span v-if="!row.transportNum">0</span>
						<el-button
							v-else
							type="primary"
							link
							@click="handleViewtransportNum(row)"
						>
							{{ row.transportNum }}
						</el-button>
					</template>

					<!-- 累计运单数插槽 -->
					<template #transportAllNum="{ row }">
						<span v-if="!row.transportAllNum">0</span>
						<el-button
							v-else
							type="primary"
							link
							@click="handleViewtransportAllNum(row)"
						>
							{{ row.transportAllNum }}
						</el-button>
					</template>
				</BasicTable>
			</div>
		</template>

		<!-- 新增/编辑弹窗 -->
		<FleetDialog
			v-model="dialogVisible"
			:edit-data="editData"
			:region-options="[{ label: '全部', value: '' }, ...xzqh]"
			@success="handleDialogSuccess"
		/>

		<!-- 车辆列表抽屉 -->
		<VehicleListDrawer
			v-model="vehicleDrawerVisible"
			:fleet-info="currentFleet"
		/>

		<!-- 运单统计抽屉 -->
		<TripStatisticsDrawer
			v-model="tripStatisticsVisible"
			:fleet-info="currentFleet"
		/>
	</WithFixedPageContainer>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
// import { Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import FleetDialog from './components/FleetDialog.vue';
import VehicleListDrawer from './components/VehicleListDrawer.vue';
import TripStatisticsDrawer from './components/TripStatisticsDrawer.vue';
import {
	getFleetPage,
	getFleetList,
	toggleFleetStatus,
} from '/@/api/tscompany/fleet';
import { useDict } from '/@/hooks/dict';

// 获取字典数据
const { xzqh } = useDict(['xzqh']);

// 弹窗相关
const dialogVisible = ref(false);
const editData = ref(null);

// 抽屉相关
const vehicleDrawerVisible = ref(false);
const tripStatisticsVisible = ref(false);
const currentFleet = ref(null);

// 搜索表单配置
const formList = computed(() => [
	{
		key: 'xzqh',
		type: 'select',
		label: '所属地区:',
		placeholder: '请选择地区',
		clearable: true,
		options: [{ label: '全部', value: '' }, ...xzqh.value],
	},
	{
		key: 'keyword',
		type: 'input-text',
		label: '关键字:',
		placeholder: '车队名称/车牌号',
		clearable: true,
		suffixIcon: 'Search',
	},
]);

// 表格列配置
const tableColumns = {
	menuWidth: 160,
	column: [
		{ label: '车队名称', prop: 'fleetName' },
		{ label: '所属地区', prop: 'xzqhName' },
		{ label: '负责人', prop: 'fleetLeader' },
		{ label: '联系电话', prop: 'telNumber' },
		{ label: '车辆数', prop: 'vehicleNum', width: 100, slot: 'vehicleNum' },
		{
			label: '本月运单数',
			prop: 'transportNum',
			width: 120,
			slot: 'transportNum',
		},
		{
			label: '累计运单数',
			prop: 'transportAllNum',
			width: 120,
			slot: 'transportAllNum',
		},
	],
};

// 分页配置
const page = reactive({
	total: 0,
	currentPage: 1,
	pageSize: 10,
});

// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 搜索参数
const searchParams = reactive({
	xzqh: '',
	keyword: '',
});

// 方法定义
function handleSearch(data) {
	console.log('Search with:', data);
	searchParams.xzqh = data.xzqh;
	searchParams.keyword = data.keyword;
	page.currentPage = 1; // 重置到第一页
	getList();
}

function handleAddNew() {
	editData.value = null;
	dialogVisible.value = true;
}

function handleEdit(row) {
	editData.value = { ...row };
	dialogVisible.value = true;
}

function handleDelete(row) {
	ElMessageBox.confirm(
		`确认要${row.status === '1' ? '禁用' : '启用'}该车队吗？`,
		'警告',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		},
	)
		.then(() => {
			toggleFleetStatus({
				id: row.id,
				fleetStatus: row.fleetStatus == '1' ? '0' : '1',
			})
				.then((response) => {
					if (response.code === 0) {
						ElMessage.success('操作成功');
						getList();
					} else {
						ElMessage.error(response.msg || '操作失败');
					}
				})
				.catch((err) => {
					console.error('操作失败:', err);
					ElMessage.error('操作失败，请重试');
				});
		})
		.catch(() => {});
}

function handleDialogSuccess(data) {
	console.log('Form submitted:', data);
	// 刷新列表
	getList();
}

function handleSizeChange(val) {
	page.pageSize = val;
	getList();
}

function handleCurrentChange(val) {
	page.currentPage = val;
	getList();
}

function getList() {
	loading.value = true;

	// 构建请求参数
	const params = {
		current: page.currentPage,
		size: page.pageSize,
		...searchParams,
	};

	// 调用API获取数据
	getFleetPage(params)
		.then((response) => {
			console.log(response, 99999);
			if (response.code === 0) {
				tableData.value = response.data.records || [];
				page.total = response.data.total || 0;
			} else {
				ElMessage.error(response.msg || '获取车队列表失败');
			}
		})
		.catch((error) => {
			console.error('获取车队列表失败:', error);
			ElMessage.error('获取车队列表失败，请重试');
		})
		.finally(() => {
			loading.value = false;
		});
}

// 获取所有车队列表（用于下拉选择等）
function getAllFleetList() {
	return getFleetList()
		.then((response) => {
			if (response.code === 0) {
				return response.data || [];
			}
			return [];
		})
		.catch((error) => {
			console.error('获取车队列表失败:', error);
			return [];
		});
}

// 查看车辆列表
function handleViewVehicles(row) {
	currentFleet.value = row;
	vehicleDrawerVisible.value = true;
}

// 查看本月运单
function handleViewtransportNum(row) {
	currentFleet.value = row;
	tripStatisticsVisible.value = true;
}

// 查看累计运单
function handleViewtransportAllNum(row) {
	currentFleet.value = row;
	tripStatisticsVisible.value = true;
}

// 初始化加载
onMounted(() => {
	getList();
});
</script>

<style scoped>
.el-input {
	--el-input-width: auto;
}
</style>
